package com.ds.common.route.context;


import com.ds.common.route.agent.Agent;
import com.ds.common.route.config.Cluster;
import com.ds.common.route.config.ConfigCenterService;
import com.ds.common.route.service.RouteCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ContextHandler {

    RouteCenterService routeCenterService;

    ConfigCenterService configCenterService;

    @Value("${spring.profiles.active}")
    private String env;

    @Autowired
    public ContextHandler(RouteCenterService routeCenterService, ConfigCenterService configCenterService) {
        this.routeCenterService = routeCenterService;
        this.configCenterService = configCenterService;
    }

    public RuntimeContext getContext(String serverName) {
        // 创建并设置上下文
        RuntimeContext context = new RuntimeContext();
        try {
            Agent agent = routeCenterService.findAgentByServerName(serverName);
            context.setAgent(agent);
            if (agent != null) {
                context.setAgentConfig(configCenterService.getAgentConfig(agent.getAgentId()));
            }
            if (!Cluster.valueOf(env).isTestEnv()) {
                context.setClusterConfig(routeCenterService.findClusterByServerName(serverName));
            } else {
                context.setClusterConfig(configCenterService.getClusterConfig(env));
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return context;
    }
}
